package com.huai.kdzhan.parentCode.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.huai.kdzhan.parentCode.po.BaseEntity;
import com.huai.kdzhan.parentCode.po.ResponseBean;
import com.huai.kdzhan.parentCode.service.ICrudService;
import com.huai.kdzhan.parentCode.utils.GenericUtil;
import com.huai.kdzhan.po.User;
import com.huai.kdzhan.util.RandomUtil;
import com.huai.kdzhan.util.SMSUtil;
import com.huai.kdzhan.util.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

public class BaseController<S extends ICrudService<T>,T extends BaseEntity> {

    @Autowired
    protected S service;

    protected Logger LOG = LoggerFactory.getLogger(this.getClass());

    //域对象类型
    protected Class<T> entityClass;

    public BaseController() {
        this.entityClass = GenericUtil.getSuperGenericClass2(this.getClass());
    }

    //分页查询
    @RequestMapping("/list")
    List<T> selectPage(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "1") int pageSize, @RequestParam(defaultValue = "null") T entity){
        PageInfo<T> pageInfo = service.selectPage(pageNum, pageSize, entity);
        List<T> list = pageInfo.getList();
        return list;
    }
    //根据手机号查询单个
    @RequestMapping("/find")
    ResponseBean selectByPhone(String phone){
        T entity = service.getBaseMapper().selectOne(new QueryWrapper<T>().eq("phone_", phone));
        ResponseBean rb = new ResponseBean();
        if (entity != null){
            rb.setResult("查找成功");
            rb.setData(entity);
        }else{
            rb.setStatus(-1);
            rb.setResult("查找失败");
        }
        return rb;
    }
    //添加
    @PostMapping("/insert")
    ResponseBean insert(T entity){
        boolean save = service.save(entity);
        ResponseBean rb = new ResponseBean();
        if (save){
            rb.setResult("添加成功");
        }else{
            rb.setStatus(-1);
            rb.setResult("添加失败");
        }
        return rb;
    }
    //根据id修改
    @PostMapping("/update")
    ResponseBean update(T entity){
        boolean update = service.updateById(entity);
        ResponseBean rb = new ResponseBean();
        if (update){
            rb.setResult("修改成功");
        }else{
            rb.setStatus(-1);
            rb.setResult("修改失败");
        }
        return rb;
    }
    //根据id删除
    @PostMapping("/delete")
    ResponseBean delete(int id){
        boolean remove = service.removeById(id);
        ResponseBean rb = new ResponseBean();
        if (remove){
            rb.setResult("删除成功");
        }else{
            rb.setStatus(-1);
            rb.setResult("删除失败");
        }
        return rb;
    }

    /**
     * 发送验证码stringCode
     * @param phone
     * @param request
     * @return
     */

    @RequestMapping("/sms")
    public ResponseBean sendSMS(String phone,HttpServletRequest request){
//        int code = RandomUtil.getCode();
        int code = 12345;
        String stringCode = Integer.toString(code);
        //根据手机号发送对应短信
//        boolean send = SMSUtil.send(phone, stringCode);
        ResponseBean rb = new ResponseBean();
        if (true){
            //发送成功，将手机号对应的验证码保存到session中
            UserUtil.setLoginSMS(request.getSession(),phone,stringCode);
            rb.setResult("短信发送成功!");
        }else {
            //发送失败
            rb.setResult("短信发送失败!");
            rb.setStatus(-1);
        }
        return rb;
    }


    /**
     * 根据密码登录
     * @param phone
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("/login/password")
    public ResponseBean userLoginByPassword(String phone,String password,HttpServletRequest request){

        ResponseBean rb = new ResponseBean();
        //判断手机号是否注册和密码是否正确
        List<T> list = service.list(new QueryWrapper<T>().eq("phone_", phone).eq("password_", password));
        //更新登录时间
        boolean update = service.update(new UpdateWrapper<T>().eq("phone_", phone).set("login_time_", new Timestamp(new Date().getTime())));

        if (list.size() == 1 && update){
            //登陆成功
            rb.setResult("登陆成功!");
        }else {
            //登陆失败
            rb.setStatus(-1);
            rb.setResult("登陆失败!");
        }

        //如果是用户登录则把用户存储到session中
        User user = new User();
        if (user.equals(entityClass)){
            user.setPhone(phone);
            UserUtil.setWxUser(request.getSession(), user);
        }else {
            UserUtil.setCourierPhone(request.getSession(), phone);
        }
        return rb;
    }

    /**
     * 根据手机号和验证码进行登录
     * @param phone
     * @param code
     * @param request
     * @return
     */
    @RequestMapping("/login/code")
    public ResponseBean userLoginByCode(String phone,String code,HttpServletRequest request){

        ResponseBean rb = new ResponseBean();
        //判断手机是否注册
        List<T> list = service.list(new QueryWrapper<T>().eq("phone_", phone));
        boolean update = service.update(new UpdateWrapper<T>().eq("phone_", phone).set("login_time_", new Timestamp(new Date().getTime())));

        if(list.size() == 1 && update){
        //判断手机号是否获取验证码
        String loginSMS = UserUtil.getLoginSMS(request.getSession(), phone);
        if (loginSMS != null){
            //判断验证码是否正确
            if (loginSMS.equals(code)){
                //验证码正确，将用户存储到session中
                //如果是用户登录则把用户存储到session中
                User user = new User();
                if (user.equals(entityClass)){
                    user.setPhone(phone);
                    UserUtil.setWxUser(request.getSession(), user);
                }else {
                    UserUtil.setCourierPhone(request.getSession(), phone);
                }
            }else {
                //验证码错误
                rb.setStatus(-1);
                rb.setResult("验证码错误,请重新发送!");
            }
        }else {
            //该手机号为获取到验证码
            rb.setStatus(-1);
            rb.setResult("该手机号为获取到验证码，请重新发送");
          }
        }else {
            rb.setStatus(-1);
            rb.setResult("该手机号未注册，请先注册!");
        }
        return rb;
    }

    /**
     * 完善认证信息
     * @param name
     * @param phone
     * @param card
     * @return
     */
    @RequestMapping("/authent")
    public ResponseBean authent(String name,String phone,String card){
        ResponseBean rb = new ResponseBean();
        boolean update = service.update(new UpdateWrapper<T>().eq("phone_", phone).set("name_", name).set("card_", card));
        if (update){
            rb.setResult("认证成功!");
        }else {
            rb.setStatus(-1);
            rb.setResult("认证失败!");
        }
        return rb;
    }
}
